/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.alibaba.druid.sql.visitor.functions.If;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.modules.tms.entity.OrderDetail;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.Torder;
import com.jeeplus.modules.tms.service.TorderService;

/**
 * 订单Controller
 * @author dhw
 * @version 2017-11-01
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/torder")
public class TorderController extends BaseController {

	@Autowired
	private TorderService torderService;

	@ModelAttribute
	public Torder get(@RequestParam(required = false) String id) {
		Torder entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = torderService.get(id);
		}
		if (entity == null) {
			entity = new Torder();
		}
		return entity;
	}

	/**
	 * 长途订单列表页面
	 */
	@RequiresPermissions("tms:torder:list")
	@RequestMapping(value = {"orderDistanceList", ""})
	public String orderDistanceList() {
		return "modules/tms/orderDistanceList";
	}

	/**
	 * 城配订单列表页面
	 */
	@RequiresPermissions("tms:torder:list")
	@RequestMapping(value = {"orderDistributionList", ""})
	public String orderDistributionList() {
		return "modules/tms/orderDistributionList";
	}

	/**
	 * 城配订单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:torder:list")
	@RequestMapping(value = "orderDistributionData")
	public Map<String, Object> orderDistributionData(Torder torder, HttpServletRequest request, HttpServletResponse response, Model model) {
		torder.setType("0");
		Page<Torder> page = torderService.findPage(new Page<Torder>(request, response), torder);
		return getBootstrapData(page);
	}

	/**
	 * 长途订单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:torder:list")
	@RequestMapping(value = "orderDistanceData")
	public Map<String, Object> orderDistanceData(Torder torder, HttpServletRequest request, HttpServletResponse response, Model model) {
		torder.setType("1");
		Page<Torder> page = torderService.findPage(new Page<Torder>(request, response), torder);
		return getBootstrapData(page);
	}

	/**
	 * 城配查看，增加，编辑订单表单页面
	 */
	@RequiresPermissions(value = {"tms:torder:view", "tms:torder:add", "tms:torder:edit"}, logical = Logical.OR)
	@RequestMapping(value = "distributionForm")
	public String distributionForm(Torder torder, Model model) {
		if (torder.getType() == null) {
			torder.setType("0");
		}
		if (torder.getCode() == null) {
			Random random = new Random();
			int rannum = (int) (random.nextDouble() * (999 - 100 + 1)) + 100;//获取三位随机数
			Date d = new Date();
			torder.setCode("60" + d.getTime() + rannum + "");
		}
		if (torder.getOrderDate() == null) {
			torder.setOrderDate(new Date());
		}
		if (torder.getStatus() == null) {
			torder.setStatus("已签收");
		}

		model.addAttribute("torder", torder);
		return "modules/tms/orderDistributionForm";
	}

	/**
	 * 长途查看，增加，编辑订单表单页面
	 */
	@RequiresPermissions(value = {"tms:torder:view", "tms:torder:add", "tms:torder:edit"}, logical = Logical.OR)
	@RequestMapping(value = "distanceForm")
	public String distanceForm(Torder torder, Model model) {
		if (torder.getType() == null) {
			torder.setType("1");
		}
		if (torder.getCode() == null) {
			Random random = new Random();
			int rannum = (int) (random.nextDouble() * (999 - 100 + 1)) + 100;//获取三位随机数
			Date d = new Date();
			torder.setCode("60" + d.getTime() + rannum + "");
		}
		if (torder.getOrderDate() == null) {
			torder.setOrderDate(new Date());
		}
		if (torder.getStatus() == null) {
			torder.setStatus("已签收");
		}
		model.addAttribute("torder", torder);
		return "modules/tms/orderDistanceForm";
	}

	/**
	 * 保存订单
	 */
	@ResponseBody
	@RequiresPermissions(value = {"tms:torder:add", "tms:torder:edit"}, logical = Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Torder torder, Model model, RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, torder)) {
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		if (torder.getType().equals("0")) {
			torder.setTotaCharge(Integer.parseInt(torder.getLoadCharge()) + Integer.parseInt(torder.getTransportCharge()) + "");
		}
		if(torder.getType().equals("1")){
			List<OrderDetail> detailList =  torder.getOrderDetailList();
			Double totalVolum =0.0;
			Double totalWeight = 0.0;
			for(OrderDetail  list: detailList){
				 totalVolum += Double.parseDouble( list.getVolume());
				totalWeight +=Double.parseDouble( list.getWeight());
			}
			torder.setTotalVolume(totalVolum+"");
			torder.setTotalWeight(totalWeight+"");
		}
		torderService.save(torder);//保存
		j.setSuccess(true);
		j.setMsg("保存订单成功");
		return j;
	}

	/**
	 * 删除订单
	 */
	@ResponseBody
	@RequiresPermissions("tms:torder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Torder torder, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		torderService.delete(torder);
		j.setMsg("删除订单成功");
		return j;
	}

	/**
	 * 批量删除订单
	 */
	@ResponseBody
	@RequiresPermissions("tms:torder:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			torderService.delete(torderService.get(id));
		}
		j.setMsg("删除订单成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:torder:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Torder torder, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "订单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Torder> page = torderService.findPage(new Page<Torder>(request, response, -1), torder);
			new ExportExcel("订单", Torder.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出订单记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public Torder detail(String id) {
		return torderService.get(id);
	}


	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("tms:torder:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Torder> list = ei.getDataList(Torder.class);
			for (Torder torder : list) {
				try {
					torderService.save(torder);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条订单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条订单记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入订单失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/tms/torder/?repage";
	}

	/**
	 * 下载导入订单数据模板
	 */
	@RequiresPermissions("tms:torder:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "订单数据导入模板.xlsx";
			List<Torder> list = Lists.newArrayList();
			new ExportExcel("订单数据", Torder.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/tms/torder/?repage";
	}


	/**
	 * 待调度城配订单列表页面
	 */
	@RequiresPermissions("tms:torder:list")
	@RequestMapping(value = {"waitDispathDistributionList", ""})
	public String waitDispathDistributionList() {
		return "modules/tms/waitDispathDistributionList";
	}


	/**
	 * 查询订单信息
	 */
	@RequestMapping(value = "findInfo")
	@ResponseBody
	public String findInfo(Torder tmsOrder, HttpServletRequest request, HttpServletResponse response){

		List<Torder> orderList = torderService.findList(tmsOrder);

		if(orderList.size()>0){
			return JsonMapper.toJsonString(orderList);
		}
		return "";
	}
	/**
	 * 根据ID查询订单信息
	 */
	@RequestMapping(value = "findTmsOrderById")
	@ResponseBody
	public String findTmsOrderById(Torder tmsOrder, HttpServletRequest request, HttpServletResponse response){
		List<Torder> orderList = new ArrayList<Torder>();
		//模态框上选中的IDS
		String ids = request.getParameter("ids");
		if(StringUtils.isNotEmpty(ids)){
			String str[] = ids.split(",");
			if(str.length>0){
				for(String id : str){
					if(StringUtils.isNotEmpty(id)){
						tmsOrder = torderService.get(id);
						orderList.add(tmsOrder);
					}
				}
			}
		}
		return JsonMapper.toJsonString(orderList);
	}
}


